package com.netmarch.jt809.utill;

/**
 * @Author:Smile
 * @Description:
 * @Date:6:13 PM2019/9/25
 */
public class CRC16Text {

    public static String getCRC(String str){
        String back="";
        int crc = 0xFFFF;
        int polynomial = 0x1021;


        String tmp="";
        byte[] bytes=new byte[str.length()/2];
        for(int i=0;i<str.length()-1;i++){
            if(i%2==0){
                tmp=str.substring(i,i+2);
                bytes[i/2]=(byte)Integer.parseInt(tmp, 16);
            }
        }


        for (byte b : bytes) {
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b   >> (7-i) & 1) == 1);
                boolean c15 = ((crc >> 15    & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit) crc ^= polynomial;
            }
        }

        crc &= 0xffff;
        back=Integer.toHexString(crc);

        return back;
    }
    public static void main(String[] args) {

        //String abc=CRC16Text.getCRC("0000001a0000000b1005000080780102010000000001");
        //String abc=CRC16Text.getCRC("0000001a000003cf1005000080780102010000000001");
        //String abc=CRC16Text.getCRC("0000001a000001551005000080780102010000000001");

        String abc=CRC16Text.getCRC("0000001f000000011002000080780102010001312d0000000004c5");
        System.out.println(new String(abc));//结果为2f7a

    }
}